<template>
  <div class="container">
    <div>
      <el-row :gutter="1">
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="公司名称：">
              <el-input
                v-model="select.CompanyName"
                placeholder="请输入公司名称"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form ref="form" :model="form" style="float: right">
            <el-form-item>
              <el-button size="mini" type="primary" @click="screeningData"
                >查 询</el-button
              >
              <el-button size="mini" type="success" @click="handleAdd"
                >新 增</el-button
              >

              <el-button style="padding: 0; border: 0">
                <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
                >
                  <el-button size="mini" type="success">导 入</el-button>
                </el-upload>
              </el-button>
              <el-button size="mini" type="warning" @click="exportExcel"
                >导 出</el-button
              >
              <!-- <el-button size="mini" type="success" @click="exportExcel">删 除</el-button> -->
              <!-- </el-form-item>
            <el-form-item> -->
              <!-- <el-form ref="form" :model="form" style="float:left"> -->
              <!-- <el-button size="mini" type="success" @click="exportExcel">导 入</el-button>
              <el-button size="mini" type="success" @click="exportExcel">导 出</el-button> -->
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      highlight-current-row
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      border
    >
      <el-table-column
        prop="CID"
        label="ID"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="CompanyName"
        label="公司名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Contacts"
        label="负责人"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="Phone"
        label="负责人电话"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="Scope"
        label="经营范围"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="StatusValue"
        label="状态"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="CarCount"
        label="现有车辆数"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- <el-button
            type="text"
            @click="handleDelete1(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 图片放大 -->
    <el-dialog
      title="图片展示"
      :visible.sync="showBigDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-image style="width: 100%; height: 100%" :src="srcBig"></el-image>
    </el-dialog>
    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="5.729vw" class="flex">
        <el-form-item label="公司名称：" class="wid50">
          <el-input
            v-model="form.CompanyName"
            placeholder="请输入公司名称"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人：" class="wid50">
          <el-input
            v-model="form.Contacts"
            placeholder="请输入负责人"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人电话：" class="wid50">
          <el-input
            v-model="form.Phone"
            placeholder="请输入负责人电话"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="经营范围：" class="wid50">
          <el-input
            v-model="form.Scope"
            placeholder="请输入经营范围"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：" class="wid50">
          <el-select v-model="form.Status" placeholder="请选择">
            <el-option
              v-for="item in rolelevel"
              :key="item.rolelevelindex"
              :label="item.roleleveltitle"
              :value="item.rolelevelindex"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'

import export2Excel from '@/utils/exportExcel/index.js'
import OSS from 'ali-oss';
import { time } from 'echarts';



export default {
  data () {

    return {
      clientData: [],
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      tableData: [],
      selectClientInfoList: [],
      expireData: [],
      select: {
        CompanyName: ''
      },
      isVisibleEdit: false,
      rolelevel: [{
        roleleveltitle: '未过审',
        rolelevelindex: '0'
      }, {
        roleleveltitle: '已过审',
        rolelevelindex: '1'
      },],
      form: {
      },
      showBigDialogVisible: false,
      srcBig: '',
      //图片上传
      fileList: [],
      VehicleUrl: '', //存上传后的公司图片url
      CBPicUrl: '', //存上传后的车本图片url
      dataObj: {
        region: 'oss-cn-beijing',//我的存储是北京，可根据具体配置自行修改
        accessKeyId: 'LTAISI12uxTRFccz',
        accessKeySecret: 'cQAvLIZ9JizT5RXRNPBVcXfg3iURD8',
        bucket: 'photo-srw-hb2',
      }, //存签名信息
      baseAli: 'oss-cn-beijing.aliyuncs.com',
    }
  },
  created () {
    if (localStorage.getItem('CTYPE') == '0') {
      this.rolelevel.shift()
    } else if (localStorage.getItem('CTYPE') != '-1') {
      this.rolelevel = []
    }
    this.getClientRoleList()
  },
  mounted () {
    this.getlistdata()
    // this.screeningData()
  },
  methods: {

    //获取公司列表
    async getlistdata () {
      var url = 'Vehicle/GetCompanyInfoZT?ClientNO=0000&CompanyName=&Contacts=&Status=-1'
      const { data } = await this.$Http.get(url)
      data.forEach(element => {
        if (element.Status === '0') {
          element.StatusValue = '未过审'
        } else {
          element.StatusValue = '已过审'
        }
      });
      this.originalData = data
      this.screeningData()
    },
    change (e) {
      this.$forceUpdate()
    },
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            console.log(ws)
            this.inputExcelDataLength = ws.length
            this.fullscreenLoading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            for (let i = 0, len = ws.length; i < len; i++) {
              var item = ws[i]
              //   var sheetData = {
              //     VID: item['居民电话'],
              //     RUBBISH_NAME: item["垃圾品名"],
              //     WEIGHT: item["垃圾称重"],
              //     photo: '',
              //     LONGITUDE: 0,
              //     LATITUDE: 0
              //   }
              //   let exceldata =  []
              //   exceldata.push(sheetData)
              this.addWeight(item)
            }
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async addWeight (item) {
      this.$axios({
        url: 'Vehicle/SaveCompanyInfoZT',
        method: 'post',
        data: {
          CompanyName: item['公司名称'],
          Contacts: item['负责人'],
          Phone: item['负责人电话'],
          Scope: item['经营范围'],
          CID: '-1',
          Status: '0',
        }
      }).then(res => {
        console.log(res)
        this.inputExcelDataIndex++
        if (res.data.IsSucess) {
          this.fullscreenLoading.close()
          this.$message.success('表格文件导入成功')
          this.getlistdata()
        } else {
          this.fullscreenLoading.close()
          this.$message.error('表格文件导入失败' + '，' + res.data.Message);

        }
        if (this.inputExcelDataIndex == this.inputExcelDataLength) {
          this.fullscreenLoading.close()
          if (this.strError.length == 0) {
            this.$message.success('表格文件导入成功')
          } else {
            // this.$message.error('表格文件导入结束<br/>' + this.strError);
            this.$message({
              message: '表格文件导入结束，' + this.strError,
              type: 'error',
              duration: 5000
            })
          }
          this.getlistdata()
        }
      })
      //   })
    },
    // 导出Excel
    exportExcel () {
      let excelName = '公司基础信息'
      const tHeader = ['公司名称', '负责人', '负责人电话', '经营范围', '状态', '现有车辆数']
      const filterVal = ['CompanyName', 'Contacts', 'Phone', 'Scope', 'StatusValue', 'CarCount']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增公司基础信息'
      //清空编辑框
      this.form = {
        CompanyName: '',
        Contacts: '',
        Phone: '',
        Scope: '',
        Status: '0',
      }
      //展示窗口
      this.isVisibleEdit = true;
      // this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = Object.assign({}, row);
      this.addDialogTitle = '编辑公司基础信息'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增公司基础信息') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 新增保存
    async saveAdd () {
      const params = {
        CID: '-1',
        CompanyName: this.form.CompanyName,
        Contacts: this.form.Contacts,
        Phone: this.form.Phone,
        Scope: this.form.Scope,
        Status: this.form.Status,
      }
      const { data } = await this.$Http.get('Vehicle/SaveCompanyInfoZT', { params })
      if (data.IsSucess) {
        this.$message.success('新增成功');
        this.isVisibleEdit = false
        this.getlistdata()
      } else {
        this.$message.error('新增失败');
      }

    },
    // 保存编辑
    async saveEdit () {
      const params = {
        CID: this.form.CID,
        CompanyName: this.form.CompanyName,
        Contacts: this.form.Contacts,
        Phone: this.form.Phone,
        Scope: this.form.Scope,
        Status: this.form.Status,
      }
      const { data } = await this.$Http.get('Vehicle/SaveCompanyInfoZT', { params })
      if (data.IsSucess) {
        this.$message.success('编辑成功');
        this.isVisibleEdit = false
        this.getlistdata()
      } else {
        this.$message.error('编辑失败');
      }
    },
    // 删除公司信息
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          ID: row.ID,
        }
        const { data } = await this.$Http.get('CarService/DeleteCarInformationInfo', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('删除失败');
        }
      } else {
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }

    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1;
      this.tableData = this.originalData
      if (this.select.CompanyName) this.tableData = this.tableData.filter(item => item.CompanyName.includes(this.select.CompanyName))
      console.log(this.select.name)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getlistdata();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    },
  }
}
</script>
<style>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.el-form-item label {
  width: 80px;
}
/* .el-upload--text {
  width: 300px;
} */
</style>